﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using EmptyWallGallery.Core.Utilities;

namespace EmptyWallGallery.Core.BLL
{
    public class QuestionListView
    {
        public int QuestionId { get; set; }
        public string QuestionName { get; set; }
        public int Status { get; set; }
        public bool MultiCheck { get; set; }
        public string CreatedBy { get; set; }
        public DateTime CreatedDate { get; set; }
        public DateTime LastUpdate { get; set; }
    }

    public class Questions
    {
        public static Questions Instance
        {
            get { return new Questions(); }
        }

        public static QuestionListView LoadDataFromListItem(Question item)
        {
            var objQuestion = new QuestionListView
                                  {
                                      QuestionName = item.QuestionName,
                                      QuestionId = Convert.ToInt32(item.QuestionId),
                                      Status = Convert.ToInt32(item.Status),
                                      MultiCheck = Convert.ToBoolean(item.MultiCheck),
                                      CreatedBy = item.CreatedBy.ToString(),
                                      CreatedDate = Convert.ToDateTime(item.CreatedDate),
                                      LastUpdate = Convert.ToDateTime(item.LastUpdate)
                                  };

            return objQuestion;
        }

        /// <summary>
        /// Create Question
        /// </summary>
        /// <param name="name">Question Name</param>
        /// <param name="createdBy">Create By</param>
        /// <param name="multiCheck">Multi Check</param>
        /// <returns></returns>
        public QuestionListView Create(string name, string createdBy, bool multiCheck)
        {
            using (var dc = new EmptyWallGalleryDataContext(Configs.ConnectionString))
            {
                var guildId = Guid.NewGuid();
                var objQuestion = new Question
                {
                    QuestionName = name,
                    CreatedBy = new Guid(createdBy),
                    CreatedDate = DateTime.Now,
                    Status = 0,
                    UniqueID = guildId,
                    LastUpdate = DateTime.Now,
                    MultiCheck = multiCheck
                };

                dc.Questions.InsertOnSubmit(objQuestion);
                dc.SubmitChanges();

                var query = (dc.Questions.Where(p => p.UniqueID == guildId)).SingleOrDefault();

                return LoadDataFromListItem(query);
            }
        }

        /// <summary>
        /// Update Question
        /// </summary>
        /// <param name="questionId">Question Id</param>
        /// <param name="name">Question Name</param>
        /// <param name="multiCheck">Multi Check</param>
        /// <returns></returns>
        public bool Update(int questionId, string name, bool multiCheck)
        {
            try
            {
                using (var dc = new EmptyWallGalleryDataContext(Configs.ConnectionString))
                {
                    var objQuestion = (dc.Questions.Where(p => p.QuestionId == questionId)).Single();
                    objQuestion.QuestionName = name;
                    objQuestion.LastUpdate = DateTime.Now;
                    objQuestion.MultiCheck = multiCheck;

                    dc.SubmitChanges();
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// Update Status Question
        /// </summary>
        /// <param name="questionId">Question Id</param>
        /// <param name="status">Question Status</param>
        /// <returns></returns>
        public bool UpdateStatus(int questionId, int status)
        {
            try
            {
                using (var dc = new EmptyWallGalleryDataContext(Configs.ConnectionString))
                {
                    var objQuestion = (dc.Questions.Where(p => p.QuestionId == questionId)).Single();
                    objQuestion.Status = status;

                    dc.SubmitChanges();
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// Delete Question
        /// </summary>
        /// <param name="questionId">Question Id</param>
        /// <returns></returns>
        public bool Delete(int questionId)
        {
            try
            {
                using (var dc = new EmptyWallGalleryDataContext(Configs.ConnectionString))
                {
                    var objQuestion = (dc.Questions.Where(p => p.QuestionId == questionId)).Single();

                    dc.Questions.DeleteOnSubmit(objQuestion);
                    dc.SubmitChanges();
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// Get All Question
        /// </summary>
        /// <returns></returns>
        public List<QuestionListView> GetQuestion()
        {
            using (var dc = new EmptyWallGalleryDataContext(Configs.ConnectionString))
            {
                var query = from q in dc.Questions
                            select new QuestionListView
                            {
                                QuestionId = int.Parse(q.QuestionId.ToString(CultureInfo.InvariantCulture)),
                                CreatedBy = q.CreatedBy.ToString(),
                                QuestionName = q.QuestionName,
                                Status = Convert.ToInt32(q.Status),
                                CreatedDate = Convert.ToDateTime(q.CreatedDate),
                                LastUpdate = Convert.ToDateTime(q.LastUpdate),
                                MultiCheck = Convert.ToBoolean(q.MultiCheck)
                            };

                return query.ToList();
            }
        }

        /// <summary>
        /// Get Question By Id
        /// </summary>
        /// <param name="questionId"></param>
        /// <returns></returns>
        public QuestionListView GetById(int questionId)
        {
            using (var dc = new EmptyWallGalleryDataContext(Configs.ConnectionString))
            {
                var query = from q in dc.Questions
                            where q.QuestionId == questionId
                            select new QuestionListView
                            {
                                QuestionId = q.QuestionId,
                                QuestionName = q.QuestionName,
                                CreatedBy = q.CreatedBy.ToString(),
                                CreatedDate = Convert.ToDateTime(q.CreatedDate),
                                LastUpdate = Convert.ToDateTime(q.LastUpdate),
                                MultiCheck = Convert.ToBoolean(q.MultiCheck),
                                Status = Convert.ToInt32(q.Status)
                            };

                return query.FirstOrDefault();
            }
        }

        /// <summary>
        /// Get Total Answer
        /// </summary>
        /// <param name="questionId">Question Id</param>
        /// <returns></returns>
        public int GetTotalAnswer(int questionId)
        {
            using (var dc = new EmptyWallGalleryDataContext(Configs.ConnectionString))
            {
                var query = (from a in dc.Answers
                             where a.QuestionId == questionId
                             select a).Count();

                return query;
            }
        }

        /// <summary>
        /// Write vote file
        /// </summary>
        public void WriteVote()
        {
            using (var dc = new EmptyWallGalleryDataContext(Configs.ConnectionString))
            {
                var questionId = (from q in dc.Questions
                             where q.Status == Convert.ToInt32(QuestionStatus.Enable)
                             orderby q.LastUpdate descending
                             select q.QuestionId).FirstOrDefault();

                var strOut = questionId == 0 ? "var voteFile = '';" : "var voteFile = '/Resource/Votes/Vote_" + questionId + ".xml';";
                var sWrite = new StreamWriter(Configs.FolderSaveData + "vote.js");
                sWrite.Write(strOut);
                sWrite.Flush();
                sWrite.Close();
            }
        }

        /// <summary>
        /// Write Question Xml
        /// </summary>
        /// <param name="questionId"></param>
        public void WriteQuestion(int questionId)
        {
            var answerItem = Answers.Instance.GetByQuestion(questionId);
            var strOut = new StringBuilder();
            foreach (var answerListView in answerItem)
            {
                strOut.Append("<item>");
                strOut.Append("<answerId>").Append(answerListView.AnsId).Append("</answerId>");
                strOut.Append("<answerName><![CDATA[").Append(
                    HttpContext.Current.Server.HtmlDecode(answerListView.AnsName)).Append(
                        " ]]></answerName>");
                strOut.Append("<total>").Append(answerListView.Total).Append("</total>");
                strOut.Append("</item>");
            }

            var questionItem = GetById(questionId);
            var strPath = Configs.VoteFile + "Vote_" + questionId + ".xml";
            var strWrite = new StreamWriter(strPath);
            strWrite.Write("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
            strWrite.Write("<vote>");
            strWrite.Write("<questionId>" + questionItem.QuestionId + "</questionId>");
            strWrite.Write("<title>" + questionItem.QuestionName + "</title>");
            strWrite.Write("<multicheck>" + questionItem.MultiCheck + "</multicheck>");
            strWrite.Write("<generator>" + Configs.WebTitle + "</generator>");
            strWrite.Write("<managingEditor>Admin</managingEditor>");
            strWrite.Write("<copyright>" + Configs.WebTitle + "</copyright>");
            strWrite.Write("<pubDate>" + Common.Instance.GetRfc822Date(DateTime.Now.AddHours(Configs.TimeLine)) +
                           "</pubDate>");
            strWrite.Write("<lastBuildDate>" +
                           Common.Instance.GetRfc822Date(DateTime.Now.AddHours(Configs.TimeLine)) +
                           "</lastBuildDate>");
            strWrite.Write(strOut.ToString());
            strWrite.Write("</vote>");
            strWrite.Flush();
            strWrite.Close();
        }

        public enum QuestionStatus
        {
            Disable = 0,
            Enable = 1
        }
    }
}
